//
//  LogInViewController.m
//  XWJSegmentController_Demo
//
//  Created by 艾玩科技 on 17/1/18.
//  Copyright © 2017年 wyp. All rights reserved.
//

#import "LogInViewController.h"
#import "MainViewController.h"

#import <AVFoundation/AVFoundation.h>
#import "QRCodeScanningVC.h"
#import "UserModel.h"
#import "CarDetailInfoView.h"

#define kDefaultHeight 71.f
#define KDefaultSize 54.f
#define KImgV_Width 50.f
#define KLeft_imgV 47.f

@interface LogInViewController ()<UITextFieldDelegate>

{
    //背景图片
    UIView *bgView;
    //手机imageview
    UIImageView *imageViewTel;
    
    UIActivityIndicatorView *indicator;
    CarDetailInfoView *carInfoV;
    
}
@property (strong, nonatomic) UITextField *usernameTextField;
@property (strong, nonatomic) UITextField *passwordTextField;
@property (strong, nonatomic) UIButton *loginButton;


@end

@implementation LogInViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"登陆";
    
    //输入手机号与密码的背景图片
//    bgView = [[UIView alloc] initWithFrame:CGRectMake(0, self.FMImgV.bottom + 80, KScreenWidth, kDefaultHeight * 2 + 1.f)];
    
    if ([UIScreen mainScreen].bounds.size.height == 480) {
        
         bgView = [[UIView alloc] initWithFrame:CGRectMake(0, self.FMImgV.bottom + 50, KScreenWidth, kDefaultHeight * 2 + 1.f)];
    }
    else
    {
         bgView = [[UIView alloc] initWithFrame:CGRectMake(0, self.FMImgV.bottom + 100, KScreenWidth, kDefaultHeight * 2 + 1.f)];
    }
    
    [self.view addSubview:bgView];
    
    [bgView addSubview:self.usernameTextField];
    [bgView addSubview:self.passwordTextField];
    [self.view addSubview:self.loginButton];
   
}




//用户名
- (UITextField*)usernameTextField
{
    if (_usernameTextField == nil) {
        //手机号textfield
        _usernameTextField = [[UITextField alloc] initWithFrame:CGRectMake(KImgV_Width + KLeft_imgV, 0.f, KScreenWidth - KImgV_Width - KLeft_imgV *2, kDefaultHeight)];
        _usernameTextField.tag = 2017020801;
        _usernameTextField.delegate = self;
#pragma mark-----------
//        _usernameTextField.text = @"17606527851";
        _usernameTextField.placeholder = @"  输入手机号";
        _usernameTextField.backgroundColor = [UIColor clearColor];
        _usernameTextField.returnKeyType = UIReturnKeyNext;
        //手机imageview
        imageViewTel = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_shouji_icon.png"]];
        imageViewTel.backgroundColor =[UIColor colorWithRed:1.000 green:0.663 blue:0.682 alpha:1.00];
        imageViewTel.frame = CGRectMake(KLeft_imgV, CGRectGetMinY(_usernameTextField.frame) + 12, KImgV_Width, KImgV_Width);
        [bgView addSubview:imageViewTel];
        //横线
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(imageViewTel.left,imageViewTel.bottom, KScreenWidth - KLeft_imgV *2  , 1)];
        line.backgroundColor = RGBACOLOR(217, 217, 217, 1);
        [bgView addSubview:line];
        
    }
    return _usernameTextField;
}
//密码
- (UITextField*)passwordTextField
{
    if (_passwordTextField == nil) {

        //密码textfield
        _passwordTextField = [[UITextField alloc] initWithFrame:CGRectMake(KImgV_Width + KLeft_imgV, imageViewTel.bottom + 3.f, KScreenWidth - KImgV_Width - KLeft_imgV *2, KImgV_Width)];
        _passwordTextField.delegate = self;
        _passwordTextField.tag = 2017020802;
        _passwordTextField.placeholder = @"  请输入密码";
        _passwordTextField.secureTextEntry = YES;
        _passwordTextField.returnKeyType = UIReturnKeyGo;
        //imgv
        UIImageView *imageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_mima_icon.png"]];
        imageView2.backgroundColor =[UIColor colorWithRed:1.000 green:0.663 blue:0.682 alpha:1.00];
        imageView2.frame = CGRectMake(KLeft_imgV, imageViewTel.bottom +3,KImgV_Width, KImgV_Width);
        [bgView addSubview:imageView2];
        //横线
        UIView *line=  [[UIView alloc] initWithFrame:CGRectMake(imageView2.left,imageView2.bottom, KScreenWidth - KLeft_imgV *2 , 1)];
        line.backgroundColor = RGBACOLOR(217, 217, 217, 1);
        [bgView addSubview:line];
    }
    return _passwordTextField;
}

//登录按钮
- (UIButton*)loginButton
{
    if (_loginButton == nil) {
        _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginButton.frame = CGRectMake(KLeft_imgV, bgView.bottom + 10.f, KScreenWidth -KLeft_imgV *2.f, 50);
        
        [_loginButton setTitle:@"登陆" forState:UIControlStateNormal];
        [_loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_loginButton setBackgroundColor:[UIColor colorWithRed:0.337 green:0.682 blue:0.961 alpha:1.00]];
        [_loginButton addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
        _loginButton.layer.cornerRadius = 3;
        _loginButton.layer.masksToBounds = YES;
        _loginButton.alpha = 0.8f;
        
    }
    return _loginButton;
}
#pragma mark - 登陆按钮的点击方法 -
-(void)loginAction
{
   
    
////     ****  -- 暂时注释掉，不可删 -- *****

    
     //手机号为0时
     if (_usernameTextField.text.length == 0  ) {
     
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"登录名不能为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
     [alert show];
     return;
     
     }
     //密码为空时
     if (_passwordTextField.text.length == 0 ) {
     
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"密码不能为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
     [alert show];
     return;
     }
    
   
     [self loadActivityView];
    
    
//    @"17606527851" @"123456"
    [CoreWork loginWithuname:self.usernameTextField.text upwd:self.passwordTextField.text deviceToken:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"deveiceTokenStr"]] deviceInfo:@"dfhgjhjk" Block:^(id responsObject) {
        
        [UMessage setAlias:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"deveiceTokenStr"]] type:@"FM" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {

        }];
#pragma mark -- 服务器报错  --
        if (![responsObject isKindOfClass:[NSDictionary class]]) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"服务器开小差了，请稍后重试" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            
            [alert addAction:sure];
            [self presentViewController:alert animated:YES completion:nil];
            //风火轮滚动结束
            [indicator stopAnimating];
            return ;
            
        }
#pragma mark -- 用户名或者密码错误 --
        if (([responsObject isKindOfClass:[NSDictionary class]] ) && ([[responsObject objectForKey:@"status"] integerValue ] == 0) ) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"%@", [responsObject objectForKey:@"message"]] preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            
            [alert addAction:sure];
            [self presentViewController:alert animated:YES completion:nil];
            //风火轮滚动结束
            [indicator stopAnimating];
            return ;
        }
#pragma mark -- ok --
        else if (([responsObject isKindOfClass:[NSDictionary class]] ) && ([[responsObject objectForKey:@"status"] integerValue ] == 1) )
        {
            NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
            [def setObject: [responsObject objectForKey:@"data"] forKey:@"userdataDic"];
            UserModel *user = [UserModel mj_objectWithKeyValues:responsObject[@"user"]];
            setUserInfo(user)
            NSLog(@"%@",GetUserLoginToken);
            
            [def setObject:[responsObject objectForKey:@"user"] forKey:@"user_user"];
            //loginToken
//            [def setObject:[[responsObject objectForKey:@"user"] objectForKey:@"loginToken"] forKey:@"user_loginToken"];
            //userid
             [def setObject:[[responsObject objectForKey:@"user"] objectForKey:@"userId"] forKey:@"user_userId"];
            
            //风火轮滚动结束
            [indicator stopAnimating];
#pragma mark 调用扫码
            //测试帐号跳过扫码
            if ([self.usernameTextField.text isEqualToString:@"17606527851"]) {
                [CoreWork signInWithloginToken:GetUserLoginToken Block:^(id responsObject) {
#pragma mark -- 服务器报错  --
                    if (![responsObject isKindOfClass:[NSDictionary class]]) {
                        
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"服务器开小差了，请稍后重试" preferredStyle:UIAlertControllerStyleAlert];
                        
                        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                        
                        [alert addAction:sure];
                        [self presentViewController:alert animated:YES completion:nil];
                        
                        return ;
                        
                    }
                    
#pragma mark --  status = 0 --
                    if (([responsObject isKindOfClass:[NSDictionary class]]) &&([[responsObject objectForKey:@"status"] integerValue] == 0)) {
                        
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"%@",[responsObject objectForKey:@"message"]] preferredStyle:UIAlertControllerStyleAlert];
                        
                        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                        
                        [alert addAction:sure];
                        [self presentViewController:alert animated:YES completion:nil];
                        
                        return ;
                        
                    }
                    //未登录
                    else   if (([responsObject isKindOfClass:[NSDictionary class]]) &&([[responsObject objectForKey:@"status"] integerValue] == -1)) {
                        
                        
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"%@",[responsObject objectForKey:@"message"]] preferredStyle:UIAlertControllerStyleAlert];
                        
                        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                        
                        [alert addAction:sure];
                        [self presentViewController:alert animated:YES completion:nil];
                        
                        return ;
                        
                    }
                    //扫描成功
                    else   if (([responsObject isKindOfClass:[NSDictionary class]]) &&([[responsObject objectForKey:@"status"] integerValue] == 1)) {
                        
                        if([[[UIDevice
                              currentDevice] systemVersion] floatValue]>=8.0) {
                            
                            self.modalPresentationStyle=UIModalPresentationOverCurrentContext;
                            
                        }
                        //设置参数判断是否已经登录
                        //    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isLogin"];
                        
                        MainViewController *mainVC = [[MainViewController alloc] init];
                        [self.navigationController pushViewController:mainVC animated:YES];
                    }
                }];
            }
            else
            {
               [self saoma];
            }

            

            
        }
        
    }];
 
    

    
}
-(void)saoma
{
    // 1、 获取摄像设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device) {
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (status == AVAuthorizationStatusNotDetermined) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        QRCodeScanningVC *vc = [[QRCodeScanningVC alloc] init];
                        [self.navigationController pushViewController:vc animated:YES];
                    });
                    
                    SGQRCodeLog(@"当前线程 - - %@", [NSThread currentThread]);
                    // 用户第一次同意了访问相机权限
                    SGQRCodeLog(@"用户第一次同意了访问相机权限");
                    
                } else {
                    
                    // 用户第一次拒绝了访问相机权限
                    SGQRCodeLog(@"用户第一次拒绝了访问相机权限");
                }
            }];
        } else if (status == AVAuthorizationStatusAuthorized) { // 用户允许当前应用访问相机
            QRCodeScanningVC *vc = [[QRCodeScanningVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        } else if (status == AVAuthorizationStatusDenied) { // 用户拒绝当前应用访问相机
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"⚠️ 警告" message:@"请去-> [设置 - 隐私 - 相机 - SGQRCodeExample] 打开访问开关" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            [alertC addAction:alertA];
            [self presentViewController:alertC animated:YES completion:nil];
            
        } else if (status == AVAuthorizationStatusRestricted) {
        }
    } else {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"未检测到您的摄像头" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertC addAction:alertA];
        [self presentViewController:alertC animated:YES completion:nil];
    }
    
    
}

#pragma mark  - UITextField Delegate -
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    UITextField *field = [textField viewWithTag:2017020802];
    //输入用户名时，usernametextfield失去第一响应者，passwordtextfield变成第一响应者
    if (textField.tag == 2017020801) {
        
        [textField resignFirstResponder];
        [field becomeFirstResponder];
        
    }
    //输入密码时，passwordtextfield失去第一响应者
    if (textField.tag == 2017020802) {
        [textField resignFirstResponder];
        //调用登录的点击方法
        [self loginAction];
        
       
    }
    return YES;
    
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_passwordTextField resignFirstResponder];
    [_usernameTextField resignFirstResponder];
}

#pragma mark --  风火轮 --
-(void)loadActivityView
{
    indicator = nil;
    indicator = (UIActivityIndicatorView *)[self.view viewWithTag:103];
    
    if (indicator == nil) {
        
        //初始化:
        indicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
        
        indicator.tag = 103;
        
        //设置显示样式,见UIActivityIndicatorViewStyle的定义
        indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
        
        
        //设置背景色
        indicator.backgroundColor = [UIColor lightGrayColor];
        
        //设置背景透明
        indicator.alpha = 0.5;
        
        //设置背景为圆角矩形
        indicator.layer.cornerRadius = 6;
        indicator.layer.masksToBounds = YES;
        //设置显示位置
        [indicator setCenter:CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0)];
        
        //开始显示Loading动画
        [indicator startAnimating];
        
        [self.view addSubview:indicator];
        
    }
    [indicator startAnimating];
}

@end
